package ar.org.cfired.creditos.gui.action;

import java.math.BigInteger;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.jbpm.api.ExecutionService;
import org.jbpm.api.ProcessEngine;
import org.jbpm.api.ProcessInstance;

import ar.org.cfired.creditos.Observaciones;
import ar.org.cfired.creditos.gui.Sesion;
import ar.org.cfired.creditos.parametros.EstadosLog;
import ar.org.cfired.creditos.parametros.GuardarParametrosException;
import ar.org.cfired.hibernate.utils.HibernateUtil;

public class GuardarModificacionYReactivarAction extends Action{
	private ExecutionService executionService;
	private ProcessEngine processEngine;
	private Logger objetoLogger = Logger.getLogger(this.getClass().getName());
	
	@Override
	public void execute(Sesion sesion) throws GuardarParametrosException {
		Session hibSession = null;
		
		try {
			hibSession = HibernateUtil.getSessionFactory().getCurrentSession();		
			hibSession.beginTransaction();
			
			EstadosLog estado = new EstadosLog();
				estado.setLogTask(BigInteger.valueOf(Integer.valueOf(sesion.getTareaActiva().getTaskID()).longValue()));
				estado.setLogUsuario(sesion.getUsuario());
				estado.setLogExecutionId((sesion.getTareaActiva().getExecutionID()==null?"a":sesion.getTareaActiva().getExecutionID()));
				estado.setEstId("AC");
			hibSession.save(estado);
			hibSession.getTransaction().commit();
		}
		catch (HibernateException e) {
			if (hibSession.getTransaction() != null)
				if (hibSession.getTransaction().isActive())
					hibSession.getTransaction().rollback();
			e.printStackTrace();
			throw new GuardarParametrosException(); 
		}
		catch (Exception e) {
			if (hibSession.getTransaction() != null)
				if (hibSession.getTransaction().isActive())
					hibSession.getTransaction().rollback();
			e.printStackTrace();
			throw new GuardarParametrosException();
		}		
	}

	@Override
	public void execute(String taskID, String usuario, String executionID)
			throws GuardarParametrosException {
		Session hibSession = null;
		try {
			hibSession = HibernateUtil.getSessionFactory().getCurrentSession();		
			hibSession.beginTransaction();
			
			
			Map<String, Object> variables = executionService.getVariables(executionID, executionService.getVariableNames(executionID));
			String exId = (String)variables.get("executionID");
			
			String instance = exId.substring(exId.indexOf(".")+1);
			if (instance.contains("."))
			instance = instance.substring(0,instance.indexOf("."));
			
			
			EstadosLog estado = new EstadosLog();
				estado.setLogTask(BigInteger.valueOf(Integer.valueOf(taskID).longValue()));
				estado.setLogUsuario(usuario);
				estado.setLogExecutionId((exId.equals("")?"a":exId));
				estado.setEstId("AC");
				estado.setLogInstance(BigInteger.valueOf(Integer.valueOf(instance).longValue()));
			hibSession.save(estado);
			
			
		
			System.out.println("Guardando variables para " + executionID);
			if (exId != null) {
				if (variables.containsKey("usuarioModificacion")) variables.remove("usuarioModificacion");
				if (variables.containsKey("executionID")) variables.remove("executionID");
				if (variables.containsKey("decision")) variables.remove("decision");
				objetoLogger.debug("Guardando variables para " + exId);
				//fuerzo la eliminacion del documento al finalizar
				if(variables.get("decision2").toString().equals("fin")){
					executionService.deleteProcessInstanceCascade(executionID);
				}
				
				List<Observaciones> observaciones = hibSession.createQuery("from Observaciones where ObsExecutionId = '" + executionID + "'").list();
				Observaciones obs;
				for (int i=0; i<observaciones.size(); i++) {
					obs = observaciones.get(i);
					obs.setObsExecutionId(exId);
					hibSession.save(obs);
				}
				
				System.out.println("Guardando variables para 2 - " + exId);
				executionService.setVariables(exId, variables);
				objetoLogger.debug("Variables guardadas (" + exId + ")");
			}
			else {
				throw new GuardarParametrosException();
			}
			
			hibSession.getTransaction().commit();
		}
		catch (HibernateException e) {
			if (hibSession.getTransaction() != null)
				if (hibSession.getTransaction().isActive())
					hibSession.getTransaction().rollback();
			e.printStackTrace();
			throw new GuardarParametrosException(); 
		}
		catch (Exception e) {
			if (hibSession.getTransaction() != null)
				if (hibSession.getTransaction().isActive())
					hibSession.getTransaction().rollback();
			e.printStackTrace();
			throw new GuardarParametrosException();
		}
	}
	
	public void setProcessEngine(ProcessEngine pe) {
		processEngine = pe;
	}
	
	public void setExecutionService(ExecutionService es) {
		executionService = es;
	}
	
	@Override
	public void execute(ExecutionService execution, String taskID, String usuario, String executionID) throws GuardarParametrosException {
		executionService = execution;
		this.execute(taskID, usuario, executionID);
	}


}
